#!/usr/bin/python

from twisted.internet import threads
import VirusWallConfig
import os
import subprocess
import sys
import time
import urllib
import urlparse


#------------ 
# unix tail link functon
#-------------
def tail_file(f_name):
    ''' unix link "tail -f "function
    14/11/2007 23:10:21 192.168.11.91 GET 304 http://2.jopenqc.com/test.cer 0+0 BLACKLIST
    14/11/2007 23:10:21 192.168.10.100 GET 200 http://k.lonoso.com/new/1.gif 407+1148 VIRUS Trend: EXPL_ANICMOO.GEN

    '''
    file = open(f_name, 'r')
    st_results = os.stat(f_name)
    st_size = st_results[6]
    file.seek(st_size)
    while 1:
        where = file.tell()
        line = file.readline()
        if not line:
            time.sleep(1)
            file.seek(where)
        else:
            analyze_havp_access_log(line)

#--------------------------
# read squid blacklist File
# BlackDomain and BlackIP
#--------------------------
def read_black_list(f=VirusWallConfig.SQUID_BLACKLIST_FILEPATH):
    black_domain = []
    black_ip = []
    return black_domain, black_ip

#-----------------------
# read white blist
#----------------------------

def read_white_list(f=VirusWallConfig.SQUID_WHITELUST_FILEPATH):
    white_domain = []
    white_ip = []
    return white_domain, white_ip

#-------------------
# Thread for process havp access.log file
#------------------
def analyze_havp_access_log(l):
    r = l.split()
    if r[7] == "BLACKLIST":
        pass
    elif r[7] == 'VIRUS':
        print l
    else:
        pass

#-------------------------
# analyze havp log main loop
# 1. read black and white list
# 2. open havp log start tail
# 3. analyze log find 'VIRUS' line
# 4. 
#-------------------------

def analyze_loop():
    

#---------------
# banner
#---------------
def banner():
    banner =  '''VirusWall Manager %s Copyright by fla.sam 2007''' % VirusWallConfig.VERSION
    return banner

#--------------
# init config and test all system
#---------------
def init_conf():
    ''' init
            1. test path , filepath , etc
            2. check backlist update
    '''
    print 'System initialize...'

    if not os.path.exists(VirusWallConfig.SQUID_PATH):
        print 'Test SQUID_PATH...False'
        sys.exit()
    else:
        print 'Test SQUID_PATH...OK'

    if not os.path.exists(VirusWallConfig.HAVP_PATH):
        print 'Test HAVP_PATH...False'
        sys.exit()
    else:
        print 'Test HAVP_PATH...OK'

#------------------------
# havp blacklist update
#------------------------
def do_really_update_balcklist():
    if VirusWallConfig.UPDATE_BLACKLIST_STAT:
        VirusWallConfig.UPDATE_BLACKLIST_STAT =False
        import time
        print 'Do really update blacklist'
        time.sleep(2)
        return True
    else:
        return False

def after_really_update_blacklist(x):
    if x:
        # set global UPDATE_BLACKLIST_STAT to True
        print 'Do Update BlackList job. Callback result: Finished'
        VirusWallConfig.UPDATE_BLACKLIST_STAT = True
    else:
        print 'Do Update BlackList job. Callback result: Not Finished,Wait.Wait.Wait.'

def update_blacklist():
    update_blacklist_job = threads.deferToThread(do_really_update_balcklist)
    update_blacklist_job.addCallback(after_really_update_blacklist)

def deploy_blacklist():
    pass

#-----------------------
# Trend virus pattern update
#-----------------------
def do_really_update_virus_pattern():
    if VirusWallConfig.UPDATE_VIRUS_PATTERN_STAT:
        VirusWallConfig.UPDATE_VIRUS_PATTERN_STAT = False
        # read virus pattern page
        r = read_web_page(VirusWallConfig.VIRUS_PATTERN_PAGE)
        # get virus pattern file url
        pattern_link = match_virus_pattern_link(read_web_page(VirusWallConfig.VIRUS_PATTERN_PAGE))
        # get virus pattern file
        get_virus_pattern(match_virus_pattern_link(pattern_link))
        # unzip virus pattern file
        deploy_virus_pattern()
        # call havp reload
        call_havp_reload_signal()

        return True
    else:
        return False

def after_really_update_virus_pattern(x):
    if x:
        print 'Do Update Virus Pattern job. Callback result: Finished'
        VirusWallConfig.UPDATE_VIRUS_PATTERN_STAT = True
    else:
        print 'Do Update Virus Pattern job. Callback result: Not Finished,Wait.Wait.Wait.'

def update_virus_pattern():
    update_virue_pattern_job = threads.deferToThread(do_really_update_virus_pattern)
    update_virue_pattern_job.addCallback(after_really_update_virus_pattern)

#-----------------------
# squid and havp running status check
#-----------------------
def do_really_check_viruswall_status():
    #subprocess.call(['%s' % VirusWallConfig.UNZIP, '-k', 'rotate'])
    pass

def after_really_check_viruswall_status():
    pass

def check_virus_scanner_ststus():
    pass

def check_http_proxy_status():
    pass
#------------------------
# squid log rotate
#------------------------
def do_really_squid_log_rotate():
    print 'Do squid log rotate'
    squid_log_roate_return = subprocess.call(['%s' %
    VirusWallConfig.SQUID_DAEMON_FILEPATH,'-k', 'rotate'])
    return squid_log_roate_return

def after_squid_log_rotate(x):
    print 'Do squid log rotate Finish. return code:%s' %x

def squid_log_rotate():
    squid_log_rotate_job = threads.deferToThread(do_really_squid_log_rotate)
    squid_log_rotate_job.addCallback(after_squid_log_rotate)

# System log marker
def marking_log():
    print '------ VirusWall Manager Mark ------'

# Function call Virus Scanner reload , when new pattern and blacklist
def call_havp_reload_signal():
    print 'OK!!! Try to reload havp...'
    kill_return_code = subprocess.call([VirusWallConfig.KILLALL, '-HUP', 'havp'])
    print 'Reload havp Done...'

# just read web page
def read_web_page(u):
    try:
        f = urllib.urlopen(urlparse.urljoin(VirusWallConfig.VIRUS_ROOT_LINK, VirusWallConfig.VIRUS_PATTERN_PAGE))
        res =  f.read()
    except IOError:
        return False
    else:
        f.close()
    return res

# match Trend Virus pattern
def match_virus_pattern_link(s):
    if VirusWallConfig.RE_VIRUS_PATTERN_OBJ.search(s):
        path = VirusWallConfig.RE_VIRUS_PATTERN_OBJ.search(s).group()
        return urlparse.urljoin(VirusWallConfig.VIRUS_ROOT_LINK, path)
    else:
        return False
# call wget to download Trend Pattern File
def get_virus_pattern(l):
    print 'Last Virus Pattenr Link: %s' % l
    wget_return_code = subprocess.call(['%s' % VirusWallConfig.WGET, '%s' % l, '-q', '-O', 'lptvpn.zip'])
    print 'Download Virus Pattern Finish'

# unzip new Trend pattern File
def deploy_virus_pattern():
    print 'Deploy Trend Virus Pattern File'
    unzip_return_code = subprocess.call(['%s' % VirusWallConfig.UNZIP, '-qq', '-o', 'lptvpn.zip', '-d', '/etc/iscan/'])
    print 'Deploy Trend Virus Pattern File.Done...'

# fake code for get blacklist
def get_blacklist(l):
    pass
# fake code for depoly blacklist
def deploy_blacklist():
    pass

